package com.longyi.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.longyi.admin.annotation.Logging;
import com.longyi.admin.common.TokenUtil;
import com.longyi.admin.entity.UserRole;
import com.longyi.admin.service.UserRoleService;
import com.longyi.admin.service.UserService;
import com.longyi.admin.entity.User;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

import com.longyi.admin.common.QueryPageParam;
import com.longyi.admin.common.Result;

/**
* User 前端控制器
*
* @author 龙毅
* @since 2025-09-08
*/
@RestController
@RequestMapping("/user")
public class UserController {

    // 注入service
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    // 统计数量
    @GetMapping("/count")
    public Integer count() {
        return userService.count();
    }

    // 获取列表
    @GetMapping("/list")
    @Logging(record = "查询用户列表", type = "查询")
    public List<User> list() {
        return userService.list();
    }

    // 新增数据
    @PostMapping("/save")
    @Logging(record = "新增用户", type = "新增")
    public Result save(@RequestBody User user) {
        List<User> list= userService.lambdaQuery().eq(User::getName, user.getName()).list();
        if(list.size()>0){
            return Result.fail("用户账号已存在");
        }
        list= userService.lambdaQuery().eq(User::getTelephone, user.getTelephone()).list();
        if(list.size()>0){
            return Result.fail("用户手机号已存在");
        }
        list= userService.lambdaQuery().eq(User::getEmail, user.getEmail()).list();
        if(list.size()>0){
            return Result.fail("用户邮箱已存在");
        }
        list= userService.lambdaQuery().eq(User::getUsername, user.getUsername()).list();
        if(list.size()>0){
            return Result.fail("用户姓名已存在");
        }
        userService.save(user);
        user.setId(userService.list().get(userService.list().size()-1).getId());
        UserRole userRole=new UserRole();
        userRole.setUserId(Long.valueOf(user.getId()));
        userRole.setRoleId(Long.valueOf(user.getRole()));
        return userRoleService.save(userRole)
            ? Result.suc("新增成功") 
            : Result.fail("新增失败");
    }

    // 修改数据
    @PostMapping("/update")
    @Logging(record = "修改用户", type = "修改")
    public Result update(@RequestBody User user) {
        List<User> list= userService.lambdaQuery().eq(User::getName, user.getName()).ne(User::getId, user.getId()).list();
        if(list.size()>0){
            return Result.fail("用户账号已存在");
        }
        list= userService.lambdaQuery().eq(User::getTelephone, user.getTelephone()).ne(User::getId, user.getId()).list();
        if(list.size()>0){
            return Result.fail("用户手机号已存在");
        }
        list= userService.lambdaQuery().eq(User::getEmail, user.getEmail()).ne(User::getId, user.getId()).list();
        if(list.size()>0){
            return Result.fail("用户邮箱已存在");
        }
        list= userService.lambdaQuery().eq(User::getUsername, user.getUsername()).ne(User::getId, user.getId()).list();
        if(list.size()>0){
            return Result.fail("用户姓名已存在");
        }
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
List<UserRole> userRoles=userRoleService.lambdaQuery().eq(UserRole::getUserId, user.getId()).list();
        System.out.println("userRoles:"+userRoles);
        UserRole userRole=userRoleService.lambdaQuery().eq(UserRole::getUserId, user.getId()).list().get(0);
        userRole.setUserId(Long.valueOf(user.getId()));
        userRole.setRoleId(Long.valueOf(user.getRole()));
        return userRoleService.updateById(userRole)
            ? Result.suc("修改成功") 
            : Result.fail("修改失败");
    }

    // 获取详情
    @GetMapping("/info/{id}")
    @Logging(record = "查询用户详情", type = "查询")
    public Result info(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        return Result.suc(user);
    }
//控制用户状态
    @PostMapping("/modStatus/{id}")
    @Logging(record = "修改用户状态", type = "修改")
    public Result modStatus(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        user.setStatus(user.getStatus()==1?0:1);
        return userService.updateById(user)?Result.suc("修改成功") : Result.fail("修改失败");
    }
    //重置密码
    @PostMapping("/repass/{id}")
    @Logging(record = "重置密码", type = "修改")
    public Result rePass(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        user.setPassword("123456");
        return userService.updateById(user)?Result.suc("重置成功") : Result.fail("重置失败");
    }
    // 批量删除数据
    @Transactional
    @PostMapping("/deleteBatch")
    @Logging(record = "批量删除用户", type = "删除")
    public Result deleteBatch(@RequestBody Long[] ids) {
        for (Long id : ids){
            User user = userService.getById(id);
            user.setStatus(0);
            userService.updateById(user);
        }
//        userService.removeByIds(Arrays.asList(ids));
        return Result.suc("批量删除成功");
    }

    // 分页查询
    @PostMapping("/listPage")
    @Logging(record = "分页查询用户列表", type = "查询")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();

        // 提取查询参数
            String id = (String) param.get("id");
            String username = (String) param.get("username");
            String name = (String) param.get("name");
            String password = (String) param.get("password");
            String telephone = (String) param.get("telephone");
            String email = (String) param.get("email");
            String age = (String) param.get("age");
            String sex = (String) param.get("sex");
            String role = (String) param.get("role");
            String status = (String) param.get("status");
            String avatar = (String) param.get("avatar");
            String createTime = (String) param.get("createTime");
            String updateTime = (String) param.get("updateTime");

        // 分页配置
        Page<User> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                if (StringUtils.isNotBlank(id) && !"null".equals(id)) {
                    lambdaQueryWrapper.eq(User::getId, id);
                }
                if (StringUtils.isNotBlank(username) && !"null".equals(username)) {
                    lambdaQueryWrapper.like(User::getUsername, username);
                }
                if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
                    lambdaQueryWrapper.like(User::getName, name);
                }
                if (StringUtils.isNotBlank(password) && !"null".equals(password)) {
                    lambdaQueryWrapper.like(User::getPassword, password);
                }
                if (StringUtils.isNotBlank(telephone) && !"null".equals(telephone)) {
                    lambdaQueryWrapper.like(User::getTelephone, telephone);
                }
                if (StringUtils.isNotBlank(email) && !"null".equals(email)) {
                    lambdaQueryWrapper.like(User::getEmail, email);
                }
                if (StringUtils.isNotBlank(age) && !"null".equals(age)) {
                    lambdaQueryWrapper.eq(User::getAge, age);
                }
                if (StringUtils.isNotBlank(sex) && !"null".equals(sex)) {
                    lambdaQueryWrapper.eq(User::getSex, sex);
                }
                if (StringUtils.isNotBlank(role) && !"null".equals(role)) {
                    lambdaQueryWrapper.eq(User::getRole, role);
                }
                if (StringUtils.isNotBlank(status) && !"null".equals(status)) {
                    lambdaQueryWrapper.eq(User::getStatus, status);
                }
                if (StringUtils.isNotBlank(avatar) && !"null".equals(avatar)) {
                    lambdaQueryWrapper.like(User::getAvatar, avatar);
                }
                if (StringUtils.isNotBlank(createTime) && !"null".equals(createTime)) {
                    lambdaQueryWrapper.like(User::getCreateTime, createTime);
                }
                if (StringUtils.isNotBlank(updateTime) && !"null".equals(updateTime)) {
                    lambdaQueryWrapper.like(User::getUpdateTime, updateTime);
                }

        // 执行分页查询
        IPage result = userService.PageList(page, lambdaQueryWrapper);
        return Result.suc(result.getTotal(), result.getRecords());
    }
    //登录接口
    @PostMapping("/login")
    @Logging(record = "用户登录", type = "登录")
    public Result login(@RequestBody User user) {
        User loginUser=new User();
        List< User> list=new ArrayList<>();
        Map<String,Object> map=new HashMap<>();
        if(StpUtil.isLogin()){
            loginUser=userService.lambdaQuery().eq(User::getUsername, user.getName()).eq(User::getPassword, user.getPassword()).list().get(0);
                if(loginUser.getStatus()==1){
                    StpUtil.login(loginUser.getId());
                    String token= TokenUtil.getTokenValue(loginUser);
                    map.put("user", loginUser);
                    map.put("token", token);
                    return Result.suc(map);

                }else{
                    return Result.fail("用户已注销");
                }

        }else{
            list=userService.lambdaQuery().eq(User::getUsername, user.getName()).eq(User::getPassword, user.getPassword()).list();
            if(list.size()>0){
                loginUser=list.get(0);
                if(loginUser.getStatus()==1){
                    StpUtil.login(loginUser.getId());
                    String token= TokenUtil.getTokenValue(loginUser);
                    map.put("user", loginUser);
                    map.put("token", token);
                    return Result.suc(map);

                }else{
                    return Result.fail("用户已注销");
                }
            }
            list=userService.lambdaQuery().eq(User::getName, user.getName()).eq(User::getPassword, user.getPassword()).list();
            if(list.size()>0){
                loginUser=list.get(0);
                if(loginUser.getStatus()==1){
                    StpUtil.login(loginUser.getId());
                    String token= TokenUtil.getTokenValue(loginUser);
                    map.put("user", loginUser);
                    map.put("token", token);
                    return Result.suc(map);

                }else{
                    return Result.fail("用户已注销");
                }
            }
            list=userService.lambdaQuery().eq(User::getEmail, user.getName()).eq(User::getPassword, user.getPassword()).list();
            if(list.size()>0){
                loginUser=list.get(0);
                if(loginUser.getStatus()==1){
                    StpUtil.login(loginUser.getId());
                    String token= TokenUtil.getTokenValue(loginUser);
                    map.put("user", loginUser);
                    map.put("token", token);
                    return Result.suc(map);

                }else{
                    return Result.fail("用户已注销");
                }
            }
            list=userService.lambdaQuery().eq(User::getTelephone, user.getName()).eq(User::getPassword, user.getPassword()).list();
            if(list.size()>0){
                loginUser=list.get(0);
                if(loginUser.getStatus()==1){
                    StpUtil.login(loginUser.getId());
                    String token= TokenUtil.getTokenValue(loginUser);
                    map.put("user", loginUser);
                    map.put("token", token);
                    return Result.suc(map);

                }else{
                    return Result.fail("用户已注销");
                }
            }

        }
        return Result.fail("用户不存在或用户名或密码错误");
    }
    //获取用户头像
    @GetMapping("/getAvatar/{name}")
    public Result getAvatar(@PathVariable String name) {
        List<User> list= userService.lambdaQuery().eq(User::getName, name).list();
        if(list.size()>0){
            return Result.suc(list.get(0).getAvatar());
        }
        list= userService.lambdaQuery().eq(User::getTelephone, name).list();
        if(list.size()>0){
            return Result.suc(list.get(0).getAvatar());
        }
        list= userService.lambdaQuery().eq(User::getEmail, name).list();
        if(list.size()>0){
            return Result.suc(list.get(0).getAvatar());
        }
        list= userService.lambdaQuery().eq(User::getUsername, name).list();
        if(list.size()>0){
            return Result.suc(list.get(0).getAvatar());
        }
        return Result.fail("用户不存在");
    }
//    注册
    @PostMapping("/register")
    @Transactional
    public Result Register(@RequestBody User user) {
        List<User> list= userService.lambdaQuery().eq(User::getName, user.getName()).list();
        if(list.size()>0){
            return Result.fail("用户账号已存在");
        }
        list= userService.lambdaQuery().eq(User::getTelephone, user.getTelephone()).list();
        if(list.size()>0){
            return Result.fail("用户手机号已存在");
        }
        list= userService.lambdaQuery().eq(User::getEmail, user.getEmail()).list();
        if(list.size()>0){
            return Result.fail("用户邮箱已存在");
        }
        list= userService.lambdaQuery().eq(User::getUsername, user.getUsername()).list();
        if(list.size()>0){
            return Result.fail("用户姓名已存在");
        }
        userService.save(user);
        user.setId(userService.list().get(userService.list().size()-1).getId());
        UserRole userRole=new UserRole();
        userRole.setUserId(Long.valueOf(user.getId()));
        userRole.setRoleId(Long.valueOf(user.getRole()));
        return userRoleService.save(userRole)?Result.suc("注册成功"):Result.fail("注册失败");
    }
    //退出登录
    @GetMapping("/logout/{id}")
    @Logging(record = "退出登录", type = "退出")
    public Result logout(@PathVariable Long id) {
        StpUtil.logout(id);
        return Result.suc("退出成功");
    }
    //注销账号
    @GetMapping("/delUser/{id}")
    @Logging(record = "注销账号", type = "注销")
    public Result delUser(@PathVariable Long id) {
        User user=userService.getById(id);
        user.setStatus(0);
        return userService.updateById(user)?Result.suc("注销成功"):Result.fail("注销失败");
    }
    //更换头像
    @GetMapping("/modAvatar")
    public Result modAvatar(@RequestParam Integer id,String avatar) {
        User user1=userService.getById(id);
        user1.setAvatar(avatar);
        return userService.updateById(user1)?Result.suc("修改成功"):Result.fail("修改失败");
    }
    //修改用户昵称
    @GetMapping("/modName")
    @Logging(record = "修改用户昵称", type = "修改")
    public Result modName(@RequestParam Integer id,String name) {
        List<User> list= userService.lambdaQuery().eq(User::getName, name).ne(User::getId, id).list();
        if (list.size()>0){
            return Result.fail("用户昵称已存在");
        }
        User user1=userService.getById(id);
        user1.setName(name);
        return userService.updateById(user1)?Result.suc("修改成功"):Result.fail("修改失败");
    }
    //修改密码
    @GetMapping("/modPwd")
    @Logging(record = "修改密码", type = "修改")
    public Result modPassword(@RequestParam Integer id,String password) {
        User user1=userService.getById(id);
        user1.setPassword(password);
        return userService.updateById(user1)?Result.suc("修改成功"):Result.fail("修改失败");
    }
}